import { reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'

interface PaginationOptions {
  useRoute?: boolean
  onChange?: (page: number, pageSize: number) => void
}
/**
 * 創建分頁配置
 * @returns 返回分頁配置對象，包含分頁參數和更新方法
 */
export const createPagination = (options: PaginationOptions = { useRoute: true }) => {
  // 默認啟用路由模式
  const route = options.useRoute ? useRoute() : null
  const router = options.useRoute ? useRouter() : null
  const handlePageChange = (page: number, pageSize: number) => {
    if (options.useRoute) {
      router?.push({
        query: {
          ...route?.query,
          page: page.toString(),
          page_size: pageSize.toString(),
        },
      })
    } else {
      options?.onChange?.(page, pageSize)
    }
  }


  const pagination = reactive({
    current: 1,
    pageSize:10,
    total: 0,
    showSizeChanger: false,
    showQuickJumper: false,
    showTotal: (total: number) => `共 ${total} 條記錄`,
    onChange: handlePageChange,
    onShowSizeChange: handlePageChange,
    updatePagination: (page: number, pageSize: number, total: number) => {
      pagination.current = page
      pagination.pageSize = pageSize
      pagination.total = total
    },
  })

  return pagination
}

// 重置分頁
export const resetPagination = (pagination: any) => {
  pagination.current = 1 // 重置當前頁碼
  pagination.pageSize = 10 // 重置每頁顯示條數
  pagination.total = 0 // 重置數據總數
}
